import http from '@/components/firstui/fui-request';
import {
	BASE_URL_DEV,
	BASE_URL
} from '@/common/config.js';
import {
	useUserStore
} from '../stores/user.js'

let host = '';
// #ifdef H5
host = process.env.NODE_ENV === "development" ? '/proxy' : BASE_URL;
// #endif

// #ifdef APP-PLUS || MP
host = process.env.NODE_ENV === "development" ? BASE_URL_DEV : BASE_URL;
// #endif

//初始化请求配置项
http.create({
	host,
	header: {},
	showLoading: false
});

//请求拦截
http.interceptors.request.use(config => {
	//请求之前可在请求头中加入token等信息
	let token = uni.getStorageSync('token') || '';
	if (!!token) {
		if (config.header) {
			config.header['Authorization'] = `Bearer ${token}`;
		} else {
			config.header = {
				'Authorization': `Bearer ${token}`
			};
		}
	}
	return config;
});

let timer = null;
//响应拦截
http.interceptors.response.use(async response => {
	const {
		data,
		skipErrorHandler,
		header
	} = response;
	if (Object.prototype.toString.call(data) === '[object Object]') {
		data.success = data.code === 200 || data.code === '200';
		if (!data.success && !skipErrorHandler) {
			uni.$fui.toast(data.message);
		}

		const token = header.Authorization || header.authorization
		if (data.success && token) {
			await useUserStore().setToken(token)
		}

		if (data.code === 401 || data.code === 402 || data.code === 403) {
			if (!timer) {
				timer = setTimeout(() => {
					uni.clearStorageSync();
					uni.reLaunch({
						url: '/pages/login/login',
						success: () => {
							uni.$fui.toast(data.message);
							timer = null;
						}
					});
				}, 300);
			}
		}
	}
	return data;
});

export default http;